package com.jiyinit.web.core.mobile.controller;

import java.text.ParseException;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.jiyinit.web.core.business.entity.TabCoreUserTask;
import com.jiyinit.web.core.business.enums.OperationTypeConstant;
import com.jiyinit.web.core.business.enums.SystemConstant;
import com.jiyinit.web.core.business.service.UserTaskServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.core.framework.base.util.JsonEntityTransform;
import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.web.core.business.dto.TaskMessageRequest;
import com.jiyinit.web.core.business.dto.TaskRequest;
import com.jiyinit.web.core.business.entity.TabCoreTask;
import com.jiyinit.web.core.business.entity.TabCoreTaskMessage;
import com.jiyinit.web.core.business.service.TaskMessageServiceImpl;
import com.jiyinit.web.core.business.service.TaskServiceImpl;
import com.jiyinit.web.core.business.vo.TaskInfoVo;
import com.jiyinit.web.core.business.vo.TaskMessageVo;
import com.jiyinit.web.core.common.logic.ParamCheckLogic;
import com.jiyinit.web.core.common.logic.ValidateResult;
import com.jiyinit.web.core.common.util.DateUtil;
import com.jiyinit.web.core.common.util.MessagePush;
import com.jiyinit.web.core.common.util.UserUtil;

/**
 * 用户管理
 *
 * @author wuyuefeng
 * @version 1.0
 * @date 2017/4/13 9:01
 * @since 1.0
 */
@Controller
@RequestMapping("/mobile/mtaskMessage")
public class MtaskMessageController {
	/**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(MtaskMessageController.class);
    
    @Resource(name = "core.taskMessageServiceImpl")
    private TaskMessageServiceImpl taskMessageServiceImpl;
    @Resource(name = "core.paramCheckLogic")
    private ParamCheckLogic paramCheckLogic;
    @Resource(name = "core.taskServiceImpl")
    private TaskServiceImpl taskServiceImpl;
    @Resource(name = "core.userTaskServiceImpl")
    private UserTaskServiceImpl userTaskServiceIml;
    
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年5月12日 上午8:49:48
         * @param 
         * @return
     */
    @RequestMapping("/mmessage")
    public ResponseEntity<ResponseDto> toTaskMessage(HttpServletRequest request,String[] alloterIds) {
    	
    	TaskMessageRequest taskMessageRequest = getJsonToTaskRequest(request);
    	List<TaskMessageVo> taskMessageVos = new ArrayList<TaskMessageVo>();
    	taskMessageVos = taskMessageServiceImpl.findTaskMesByTaskId(taskMessageRequest);

    	if (taskMessageVos.size() > 0) {
            return new ResponseEntity<>(ResponseDto.responseOK(taskMessageVos), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseOK(taskMessageVos), HttpStatus.OK);
    }
    
    
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年5月12日 上午8:49:48
         * @param 
         * @return
     */
    @RequestMapping("/mmessageForPage")
    public ResponseEntity<ResponseDto> messageForPage(HttpServletRequest request) {
    	TaskMessageRequest taskMessageRequest = getJsonToTaskRequest(request);
    	
    	if(taskMessageRequest.getLimit()==0){
    		taskMessageRequest.setLimit(10);
    	}
    	
        PagingResult<TaskMessageVo> pagingResult = taskMessageServiceImpl.messageForPage(taskMessageRequest);
        LogUtil.info(LOGGER, "getTotalRecords:{},getTotalPages:{},getRows:{}", pagingResult.getTotalRecords(), pagingResult.getTotalPages(),pagingResult.getRows());
        if(pagingResult.getTotalRecords()>0)
        	return new ResponseEntity<>(ResponseDto.responseOK(pagingResult), HttpStatus.OK);
        return new ResponseEntity<>(ResponseDto.responseFail("failed"), HttpStatus.OK);
    }
    
    
    
    
    @ResponseBody
    @RequestMapping("/maddMessage")
    public ResponseEntity<ResponseDto> addMessage(HttpServletRequest request) {
  
    	TaskMessageRequest taskMessageRequest = getJsonToTaskRequest(request);

    	ValidateResult<TaskMessageRequest> validateResult = paramCheckLogic.checkParamValidate(taskMessageRequest);
        if (!validateResult.isSuccess()) {
            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
        }
        
        TabCoreTaskMessage tabCoreTaskMessage = new TabCoreTaskMessage();
        BeanUtils.copyProperties(taskMessageRequest, tabCoreTaskMessage);
        //查找任务内容
        Integer taskId = taskMessageRequest.getTaskId();
        TabCoreTask tabCoreTask = taskServiceImpl.findTaskById(taskId);
        
       
//        Integer currentUid = UserUtil.getCurrentUser().getUserId();
        Integer currentUid = taskMessageRequest.getCreateUid();
        //根据taskId 从后台查询，所有参与者
        List<TabCoreUserTask> list =userTaskServiceIml.getUserByTaskId(taskId);
        HashSet<String> canyurenIds = new HashSet<>();
        String aIdsStr = "";

        for(TabCoreUserTask usertask : list){
        	if(currentUid.intValue() != usertask.getAlloterId().intValue()){
                canyurenIds.add(usertask.getAlloterId()+"");
        	}
        }
        if(currentUid.intValue() != tabCoreTask.getCreateUid().intValue()){ //当前说说的登录者，是任务的创建人
            canyurenIds.add(tabCoreTask.getCreateUid()+"");
        }
        String[]  alloterIds = canyurenIds.toArray(new String[canyurenIds.size()]);
        
        Integer taskUid = taskMessageRequest.getTaskUid();
        if(taskUid!=currentUid){
        	tabCoreTaskMessage.setMessageCla("leftBubble");
        }else{
        	tabCoreTaskMessage.setMessageCla("rightBubble");
        }
        tabCoreTaskMessage.setCreateTime(new Date());
        tabCoreTaskMessage.setCreateUid(currentUid);


//        tabCoreTask.setStatus(taskMessageRequest.getTaskStatus());
        //只更新最后修改时间
        TabCoreTask task = new TabCoreTask();
        task.setTaskId(tabCoreTask.getTaskId());
        task.setEditTime(new Date());
        
        int num = 0;
        num = taskMessageServiceImpl.maddTaskMessage(tabCoreTaskMessage,task,alloterIds);
        
    	if (num > 0) {
    		Integer responserId = taskMessageRequest.getResponserId();
    		
    		
    		Map<String,String> returnStr = new HashMap<>();
    		
    		returnStr.put("taskTitle", tabCoreTask.getTitle());
    		returnStr.put("taskId", tabCoreTask.getTaskId().toString());
    		returnStr.put("createUid", tabCoreTask.getCreateUid().toString());
    		returnStr.put("strikeType", taskMessageRequest.getStrikeType());
    		returnStr.put("type", OperationTypeConstant.TASK_ADD_MESSAGE);
    		returnStr.put("dsc", tabCoreTask.getDescription());
    		returnStr.put("taskStatus", taskMessageRequest.getTaskStatus());
            returnStr.put("content", "任务:"+tabCoreTask.getTitle()+",有内容更新:"+taskMessageRequest.getMessageContent());
            Integer taskCla=taskServiceImpl.findTaskById(task.getTaskId()).getTaskCla();
            returnStr.put("taskCla", String.valueOf(taskCla));
    		if (taskCla.intValue()==66){
                if(taskMessageRequest.getChannel()!=null&&taskMessageRequest.getChannel().equals("01")){
                    //MessagePush messagePush = new MessagePush(returnStr,new String[]{responserId.toString()});
                    MessagePush messagePush = new MessagePush(returnStr,alloterIds);
                }else{
                    MessagePush messagePush = new MessagePush(returnStr,alloterIds,"andriod");
                }
            }
            return new ResponseEntity<>(ResponseDto.responseOK("success"), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail("failed"), HttpStatus.OK);
    }
    
    private TaskMessageRequest getJsonToTaskRequest(HttpServletRequest request){
    	String logJson = request.getParameter("request_json");
    	LogUtil.info(LOGGER, "logJson:{}", logJson);
    	TaskMessageRequest taskMessageRequest = (TaskMessageRequest)JsonEntityTransform.json2Object(logJson, TaskMessageRequest.class);
    	return taskMessageRequest;
    }
}
